package com.github_dididipapa.mall.product.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github_dididipapa.common.constant.ProductConstant;
import com.github_dididipapa.common.exception.ElasticSearchException;
import com.github_dididipapa.common.to.SkuReductionTo;
import com.github_dididipapa.common.to.SpuBoundTo;
import com.github_dididipapa.common.to.WareSkuTo;
import com.github_dididipapa.common.to.es.SkuEsModel;
import com.github_dididipapa.common.utils.R;
import com.github_dididipapa.mall.product.entity.*;
import com.github_dididipapa.mall.product.feign.CouponFeignService;
import com.github_dididipapa.mall.product.feign.ElasticFeignService;
import com.github_dididipapa.mall.product.feign.WareFeignService;
import com.github_dididipapa.mall.product.service.*;
import com.github_dididipapa.mall.product.vo.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github_dididipapa.common.utils.PageUtils;
import com.github_dididipapa.common.utils.Query;
import com.github_dididipapa.mall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

@Slf4j
@RequiredArgsConstructor
@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {
    @Lazy
    @Autowired
    private SpuInfoService spuInfoService;
    private final SpuImagesService spuImagesService;
    private final AttrService attrService;
    private final ProductAttrValueService productAttrValueService;
    private final SkuInfoService skuInfoService;
    private final SkuImagesService skuImagesService;
    private final SkuSaleAttrValueService skuSaleAttrValueService;
    private final CouponFeignService couponFeignService;
    private final WareFeignService wareFeignService;
    private final SpuInfoDescService spuInfoDescService;
    private final ElasticFeignService elasticFeignService;
    private final BrandService brandService;
    private final CategoryService categoryService;

    @Autowired
    private SpuInfoDao spuInfoDao;

    @Override
    public PageUtils queryPageCondition(Map<String, Object> params) {
        String key = (String) params.get("key");
        String catelogId = (String) params.get("catelogId");
        String brandId = (String) params.get("brandId");
        String status = (String) params.get("status");
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();
        if(StringUtils.hasText(key)){
            wrapper.and(innerSql  -> {
                innerSql.eq("id", key)
                        .or().
                        like("spu_name", key);
            });
        }

        if(StringUtils.hasText(catelogId) && !"0".equalsIgnoreCase(catelogId)){
            wrapper.eq("catelog_id", catelogId);
        }
        if(StringUtils.hasText(brandId) && !"0".equalsIgnoreCase(brandId)){
            wrapper.eq("brand_id", brandId);
        }
        if(StringUtils.hasText(status)){
            wrapper.eq("publish_status", status);
        }

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }


    /**
     * @description: 商品上架，推送商品数据到ES
     * @author: dididi_papa
     * @date: 2025/7/3 下午5:53
     * @param: [spuId]
     * @return: void
     **/
    @Transactional(
            rollbackFor = {ElasticSearchException.class, RuntimeException.class}
    )
    @Override
    public void up(Long spuId) {
        //1.查出所有spuId对应的所有sku信息、品牌的名字
        List<SkuInfoEntity> skuInfoEntityList = skuInfoService.list(
                new QueryWrapper<SkuInfoEntity>()
                        .eq("spu_id", spuId));

        List<Long> skuIds = skuInfoEntityList
                .stream()
                .map(SkuInfoEntity::getSkuId)
                .collect(Collectors.toList());

        //查询所有spuId对应的规格属性
        List<ProductAttrValueEntity> attrValueEntities = productAttrValueService.baseAttrListForSpu(spuId);
        //抽取出attrValueEntities所有attrId到一个List集合中
        List<Long> attrIds = attrValueEntities.stream()
                .map(ProductAttrValueEntity::getAttrId)
                .collect(Collectors.toList());
        List<Long> attrs = attrService.getBaseAttrs(attrIds);
        Set<Long> set = new HashSet<>(attrs);

        List<com.github_dididipapa.common.to.component.Attr> attrList = attrValueEntities.stream()
                .filter(item -> set.contains(item.getAttrId()))
                .map(item -> {
                    com.github_dididipapa.common.to.component.Attr attr = new com.github_dididipapa.common.to.component.Attr();
                    BeanUtil.copyProperties(item, attr);
                    return attr;
                })
                .collect(Collectors.toList());
        //查出哪些商品有库存
        List<SkuHasStockVo> hasStockList =  wareFeignService.getSkusHasStock(skuIds);
        //封装成map, 哈希查找速度更快，优化stream流的执行效率
        Map<Long, Boolean> hasStockMap = hasStockList.stream()
                .collect(Collectors.toMap(SkuHasStockVo::getSkuId, SkuHasStockVo::getHasStock));


        //2.封装sku信息
        List<SkuEsModel> upProducts = skuInfoEntityList.stream().map(item -> {
            SkuEsModel model = new SkuEsModel();
            BeanUtils.copyProperties(item, model);
            //需要处理的属性： SpuPrice,skuImg, hasStock, hotScore, arrts
            model.setSpuPrice(item.getPrice());
            model.setSkuImg(item.getSkuDefaultImg());

            //设置库存信息
            model.setHasStock(hasStockMap.getOrDefault(item.getSkuId(), false));
            // 设置热度评分
            model.setHotScore(0L);

            // 查询品牌和分类的名字信息
            BrandEntity brand = brandService.getById(item.getBrandId());
            model.setBrandName(brand.getName());
            model.setBrandImg(brand.getLogo());

            CategoryEntity category = categoryService.getById(item.getCatelogId());
            model.setCatelogName(category.getName());

            // 设置attrs
            model.setAttrs(attrList);
            return model;
        }).collect(Collectors.toList());

        //3.保存到ES
        R r = elasticFeignService.saveSpu(upProducts);
        if (r.getCode() == 0) {
            // 保存成功
            //4.数据库中修改商品状态为上架
            spuInfoDao.updateSpuStatus(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());
        }
        else {
            //保存失败
            // TODO: 幂等性问题、重复调用
            throw new RuntimeException("保存失败");
        }

    }

    //保存新发布的商品信息
    @Transactional
    @Override
    public void saveSpuInfoDetail(SpuInfoSaveVo vo) {
        //1、保存spu基本信息`pms_spu_info`
        SpuInfoEntity infoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(vo, infoEntity);
        infoEntity.setCreateTime(new Date());
        infoEntity.setUpdateTime(new Date());
        spuInfoService.save(infoEntity);

        //2、保存spu的描述图片`pms_spu_info_desc`
        List<String> decript = vo.getDecript();
        SpuInfoDescEntity descEntity = new SpuInfoDescEntity();
        descEntity.setSpuId(infoEntity.getId());
        descEntity.setDecript(String.join(",", decript));
        spuInfoDescService.save(descEntity);

        //3、保存spu的图片集`pms_spu_images`
        List<String> images = vo.getImages();
        if (images != null && images.size() != 0) {
            List<SpuImagesEntity> collect = images.stream().map(image -> {
                SpuImagesEntity imagesEntity = new SpuImagesEntity();
                imagesEntity.setSpuId(infoEntity.getId());
                imagesEntity.setImgUrl(image);
                return imagesEntity;
            }).collect(Collectors.toList());
            spuImagesService.saveBatch(collect);
        }

        //4、保存spu的规格参数`pms_product_attr_value`
        List<BaseAttr> baseAttrs = vo.getBaseAttrs();
        List<ProductAttrValueEntity> productAttrValueEntityList = baseAttrs.stream().map(attr -> {
            ProductAttrValueEntity valueEntity = new ProductAttrValueEntity();
            valueEntity.setAttrId(attr.getAttrId());
            AttrEntity byId = attrService.getById(attr.getAttrId());
            valueEntity.setAttrName(byId.getAttrName());
            valueEntity.setAttrValue(attr.getAttrValues());
            valueEntity.setQuickShow(attr.getShowDesc());
            valueEntity.setSpuId(infoEntity.getId());
            return valueEntity;
        }).collect(Collectors.toList());
        productAttrValueService.saveBatch(productAttrValueEntityList);


        //5、保存spu的积分信息`gulimall_sms`->`sms_spu_bounds`
        Bounds bounds = vo.getBounds();
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        BeanUtils.copyProperties(bounds, spuBoundTo);
        spuBoundTo.setSpuId(infoEntity.getId());
        R r = couponFeignService.saveSpuBounds(spuBoundTo);
        if (r.getCode() != 0){
            log.error("远程保存spu积分信息失败");
        }

        //6、保存spu对应的所有sku信息
        List<Sku> skus = vo.getSkus();
        if (skus != null && skus.size() > 0) {
            skus.forEach(item -> {
                String defaultImg = "";
                //查找出默认图片
                for (Images image : item.getImages()) {
                    if (image.getDefaultImg() == 1) {
                        defaultImg = image.getImgUrl();
                    }
                }
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(item, skuInfoEntity);
                skuInfoEntity.setSpuId(infoEntity.getId());
                skuInfoEntity.setBrandId(infoEntity.getBrandId());
                skuInfoEntity.setCatelogId(infoEntity.getCatelogId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSkuDefaultImg(defaultImg);
                //6.1、sku的基本信息`pms_sku_info`
                skuInfoService.save(skuInfoEntity);

                //6.2、sku的图片信息`pms_sku_images`
                Long skuId = skuInfoEntity.getSkuId();

                List<SkuImagesEntity> skuImagesEntities = item.getImages().stream().map(img -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setImgUrl(img.getImgUrl());
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());
                    return skuImagesEntity;
                }).filter(entity -> {
                    //返回true是需要，返回false是过滤掉
                    return !com.mysql.cj.util.StringUtils.isNullOrEmpty(entity.getImgUrl());
                }).collect(Collectors.toList());
                skuImagesService.saveBatch(skuImagesEntities);

                //6.3、sku的销售属性信息`pms_sku_sale_attr_value`
                List<Attr> attr = item.getAttr();
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attr.stream().map(a -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    skuSaleAttrValueEntity.setSkuId(skuId);
                    BeanUtils.copyProperties(a, skuSaleAttrValueEntity);
                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);


                //6.4、sku的优惠、满减等信息`gulimall_sms`->`sms_sku_ladder`/`sms_sku_full_reduction`/`sms_member_price`
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(item, skuReductionTo);
                skuReductionTo.setSkuId(infoEntity.getId());
                if (skuReductionTo.getFullCount() > 0 || skuReductionTo.getFullPrice().compareTo(new BigDecimal("0")) == 1){
                    R r1 = couponFeignService.saveSkuReduction(skuReductionTo);
                    if (r1.getCode() != 0){
                        log.error("远程保存优惠信息失败");
                    }
                }
            });
        }
    }




}